package thesis.javaclass;

import java.util.ArrayList;
import java.util.List;

import thesis.database.Factory;
import thesis.database.TaxiJDBCTemplate;

public class FindTaxiServer implements Runnable {
	private ServiceRequest serviceRequest;
	TaxiJDBCTemplate taxi = (TaxiJDBCTemplate) Factory
			.createJDBCTemplate("taxiJDBCTemplate");

	public FindTaxiServer(ServiceRequest serviceRequest) {
		this.serviceRequest = serviceRequest;
	}

	public void run() {

		double distance = 1.5;
		do {
			boolean flag = true; // this flag is mean that it does not exist
			// any free taxi
			// gui thong tin den Server
			ArrayList<Double> boudingCoordinate = MapFunction
					.getBoundingCoordinates(
							serviceRequest.getCoordinate().get(0),
							serviceRequest.getCoordinate().get(1), distance);
			TaxiJDBCTemplate taxiTem = (TaxiJDBCTemplate) Factory
					.createJDBCTemplate("taxiJDBCTemplate");
			List<Integer> listId = taxiTem.getListTaxiIdByBoundingCoordinates(
					boudingCoordinate.get(0), boudingCoordinate.get(1),
					boudingCoordinate.get(2), boudingCoordinate.get(3),
					serviceRequest.getNumberOfSeat());

			// dinh dang chuoi gui di :
			// phoneNumber-address-latitudeOfCustomer-longitudeOfCustomer-taxiId-taxiId----taxiid;

			// /get port by id to send to taxi listener for demo///////
			// ///////////////////////////////////////////////////////
			if (listId.size() > 0) {

				for (int i = 0; i < listId.size(); i++) {
					// System.out.println(ServiceList.isBusy(taxi.getImeiById(listId.get(i))));
					if (!ServiceList.isBusy(taxi.getImeiById(listId.get(i)))) {
						flag = false;// note that there is exist at least one
										// free taxi

						ServiceList.setBusy(taxi.getImeiById(listId.get(i)));
						BroadcastServer bs = new BroadcastServer(
								taxi.getPortById(listId.get(i)),
								taxi.getImeiById(listId.get(i)),
								taxi.getNumberPlateById(listId.get(i)),
								serviceRequest);
						Thread thread = new Thread(bs);
						thread.start();
					}

				}
				if (flag) {
					System.out.println(Thread.currentThread().getName()
							+ " : R = " + distance + " : All taxies are busy");
				}
			} else {
				System.out.println("R = " + distance + ": not found any taxi");
			}
			try {
				Thread.currentThread();
				Thread.sleep(20000); // 15s for confirm first time;
				if (serviceRequest.getAcceptTaxiImeis().size() != 0)
					serviceRequest.setFinished(true);
				int count = 0;
				while (true) {
					Thread.sleep(1);
					count++;
					if (count == 17000
							|| serviceRequest.getSelectedImei() != "") {
						break;
					}

				}

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (serviceRequest.getSelectedImei().equals(""))
				clearData();
			distance += 1.5;
		} while (serviceRequest.getSelectedImei().equals(""));

	}

	private void clearData() {
		serviceRequest.getAcceptTaxiImeis().clear();
		serviceRequest.setFinished(false);
	}
}
